<template>
  <div class="home-page">
    <header class="header">
      <a-dropdown>
        <a class="ant-dropdown-link" href="#">
          {{ renderUserName() }} <a-icon type="down" />
        </a>
        <a-menu slot="overlay">
          <a-menu-item>
            <a href="javascript:;" @click="handleLogout">退出登录</a>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </header>
    <section class="section">
      <div class="editor-field">
        <a-radio-group v-model="radioVal" buttonStyle="solid" class="radio-field">
          <a-radio-button value="richText">富文本</a-radio-button>
          <a-radio-button value="markdown">Markdown</a-radio-button>
        </a-radio-group>
        <!-- 富文本编辑器 -->
        <quill-editor
          v-if="radioVal === 'richText'"
          v-model="richTextVal"
          ref="myQuillEditor"
        >
        </quill-editor>
        <!-- markdown编辑器 -->
        <mavon-editor v-else v-model="markdownVal"/>
        <a-button class="btn" type="primary" @click="handleSubmit">提交</a-button>
      </div>
      <div class="article-list">
        <div class="list-header">
          <strong>我的文章</strong>
          <a-button type="primary" :disabled="!articleList.length" @click="handleExportXlsx">导出表格</a-button>
        </div>
        <a-table
          :rowKey="record => record._id"
          class="table-field"
          :columns="columns"
          :dataSource="articleList"
          :pagination="paginationConf"
          :loading="loading"
        >
          <span slot="publishTime" slot-scope="text">{{ moment(text).format('YYYY/MM/DD HH:mm:ss') }}</span>
          <span slot="contentType" slot-scope="text">{{ text | filterContentType }}</span>
          <span slot="options" slot-scope="text, record">
            <a href="javascript: void(0);" @click="goDetail(record._id)">查看</a>
            <span v-if="record.canOperate">
              <a-divider type="vertical" />
              <a href="javascript: void(0);" @click="goEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a href="javascript: void(0);" @click="goDelete(record._id)">删除</a>
            </span>
          </span>
        </a-table>
      </div>
    </section>
  </div>
</template>

<script>
import moment from 'moment'
import qs from 'qs'
import { exportFile } from '@/assets/utils'
const columns = [{
  title: '用户名',
  dataIndex: 'userName'
}, {
  title: '发布时间',
  dataIndex: 'publishTime',
  scopedSlots: { customRender: 'publishTime' }
}, {
  title: '内容类型',
  dataIndex: 'contentType',
  scopedSlots: { customRender: 'contentType' }
}, {
  title: '操作',
  dataIndex: 'options',
  scopedSlots: { customRender: 'options' }
}]
export default {
  data () {
    return {
      columns,
      radioVal: 'richText',
      richTextVal: '',
      markdownVal: '',
      articleList: [],
      paramsInfo: {
        page: 1,
        rows: 10
      },
      paginationConf: {
        current: 1,
        pageSize: 10,
        total: 0,
        showQuickJumper: true,
        size: 'small'
        // hideOnSinglePage: true
      },
      loading: false,
      isEdit: false,
      editId: undefined
    }
  },
  methods: {
    moment,
    async getArticleList () {
      this.loading = true
      const res = await this.$http.get('/article/get', { params: this.paramsInfo })
      this.loading = false
      const { code, message = [], current = 1,pageSize = 10, total = 0 } = res
      if (code === 200) {
        this.articleList = message
        const options = {
          current,
          pageSize,
          total,
          onChange: this.getArticleList
        }
        this.paramsInfo = {
          page: current,
          rows: pageSize
        }
        Object.assign(this.paginationConf, options)
      }
    },
    async handleSubmit () {
      const isRichText = this.radioVal === 'richText'
      if (isRichText && !this.richTextVal) {
        return this.$message.warn('请输入富文本内容')
      }
      if (!isRichText && !this.markdownVal) {
        return this.$message.warn('请输入markdown内容')
      }
      const content = isRichText ? this.richTextVal : this.markdownVal
      const paramsObj = { content, contentType: this.radioVal }
      let method = 'post', url = '/article/add'
      if (this.isEdit) {
        paramsObj.id = this.editId
        method = 'put'
        url = '/article/edit'
      }
      const res = await this.$http[method](url, paramsObj)
      if (res.code === 200) {
        this.$message.success(res.message)
        this.richTextVal = ''
        this.markdownVal = ''
        this.paginationConf.page = 1
        this.getArticleList()
        this.isEdit = false
      } else {
        this.$message.warn(res.message)
      }
    },
    goDetail (id) {
      this.$router.push({ name: 'txtDetail', query: { id } })
    },
    renderUserName () {
      if (document.cookie) {
        const regExp = /; /gm
        const cookieStr = document.cookie.replace(regExp, '&')
        return qs.parse(cookieStr).name
      }
      return '--'
    },
    async handleLogout () {
      const res = await this.$http.post('/user/logout')
      const { code, message } = res
      if (res.code === 200) {
        this.$message.success(res.message)
        this.$router.push({ name: 'login' })
      } else {
        this.$message.warn(res.message)
      }
    },
    goEdit (record) {
      this.isEdit = true
      const { _id, rawContent, contentType } = record
      this.editId = _id
      this.radioVal = contentType
      if (contentType === 'richText') {
        this.richTextVal = rawContent
      } else {
        this.markdownVal = rawContent
      }
    },
    goDelete (id) {
      this.$confirm({
        title: '删除文章',
        content: '确认删除该文章吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          const res = await this.$http.delete('/article/delete')
          const { code, message } = res
          if (res.code === 200) {
            this.$message.success(res.message)
            this.getArticleList()
          } else {
            this.$message.warn(res.message)
          }
        },
        onCancel () {
          console.log('Cancel');
        },
      });
    },
    async handleExportXlsx () {
      const res = await this.$http.get('/article/export')
      if (res.code === 200) {
        exportFile(`https://www.chensai.club/downloads/xlsx_${res.message}.xlsx`)
      }
    }
  },
  created () {
    this.getArticleList()
  }
}
</script>

<style scoped lang="less">
.home-page {
  .header {
    padding: 24px;
    background-color: #eee;
    height: 60px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .section {
    padding: 24px;
    display: flex;
    .radio-field {
      margin-bottom: 24px;
    }
    .editor-field {
      flex: 2;
    }
    .btn,
    .table-field {
      margin-top: 24px;
    }
    .article-list {
      margin-left: 24px;
      flex: 1;
      .list-header {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>